package com.yanqingying.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import com.yanqingying.JwtsTest;
import com.yanqingying.*;
import com.yanqingying.mapper.EmpExprMapper;
import com.yanqingying.mapper.EmpMapper;
import com.yanqingying.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    EmpExprMapper empExprMapper;
    @Autowired
    EmpMapper empMapper;
    public PageBean page(EmpQueryParam param){
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<Emp> pageBeans =empMapper.list(param);
        Page<Emp> p = (Page<Emp>) (pageBeans);
        return new PageBean(p.getTotal(),p.getResult());
    }
    @Transactional
    @Override
    public void add(Emp emp) {
        emp.setPassword("123456");
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.add(emp);
        Integer id = emp.getId();
        log.info("id是"+id);
        List<ExpExpr> exprList = emp.getExprList();
        if (!CollectionUtils.isEmpty(exprList)) {
            exprList.forEach((expExpr -> expExpr.setEmpId(id)));
            empExprMapper.insertBatch(exprList);

        }
    }
    @Transactional
    @Override
    public void delete(List<Integer> ids) {
        empMapper.delete(ids);
        empExprMapper.delete(ids);
    }

    @Override
    public Emp getsId(Integer id) {
        return empMapper.getsId(id);
    }
    @Transactional
    @Override
    public void upDate(Emp id) {
        id.setUpdateTime(LocalDateTime.now());
        empMapper.upLoad(id);
        empExprMapper.delete(Arrays.asList(id.getId()));
        List<ExpExpr> exprList = id.getExprList();
        if(!CollectionUtils.isEmpty(exprList)){
            exprList.forEach(expExpr -> {
                expExpr.setEmpId(id.getId());
            });
            empExprMapper.insertBatch(exprList);
        }
    }

    @Override
    public LoginInfo login(Emp emp) {
        LoginInfo loginClan = empMapper.login(emp);
        if (loginClan != null) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("username", loginClan.getId());
            claims.put("passWord", loginClan.getUsername());
            String jwt = JwtsTest.JwtBuild(claims);
            LoginInfo loginInfo = new LoginInfo(loginClan.getId(),
                    loginClan.getUsername(), loginClan.getName(),jwt );
            return loginInfo;
        }
        return null;
    }

}
